package org.kitten.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author uniquejava@gmail.com
 * @since 2007-8-28
 */
public class StringUtil {
	public static final String EMPTY = "";

	private StringUtil() {
	}

	public static String get(Object source) {
        return isNotBlank(source)? source.toString().trim():"";
    }

    public static String get(Object source, String defaultString) {
        return isNotBlank(source)? source.toString().trim():defaultString;
    }

    
	public static String nvl(Object source) {
		return (source != null) ? source.toString().trim() : "";
	}

	public static String nvl(Object source, String defaultString) {
		return (source != null) ? source.toString().trim() : defaultString;
	}

	public static int nvl(Object source, int defaultValue) {
		String str = nvl(source, String.valueOf(defaultValue));
		return Integer.parseInt(str);
	}

	public static float nvl(Object source, float defaultValue) {
		String str = nvl(source, String.valueOf(defaultValue));
		return Float.parseFloat(str);
	}

	public static double nvl(Object source, double defaultValue) {
		String str = nvl(source, String.valueOf(defaultValue));
		return Double.parseDouble(str);
	}

	public static boolean isEmpty(Object msg) {
		return (msg == null) || msg.equals("");
	}

	public static boolean isNotEmpty(Object msg) {
		return (msg != null) && !msg.equals("");
	}

	public static boolean isBlank(Object msg) {
		return (msg == null) || String.valueOf(msg).trim().length() == 0;
	}

	public static boolean isNotBlank(Object msg) {
		return (msg != null) && String.valueOf(msg).trim().length() != 0;
	}

	/**
	 * 左填充.详细用法见oracle lpad函数
	 * 
	 * @param source
	 * @param padStr
	 * @param finalLength
	 * @return
	 */
	public static String lpad(String source, String padStr, int finalLength) {
		String ret = source;
		while (ret.length() < finalLength) {
			ret = padStr + ret;
		}
		return ret;
	}

	/**
	 * 右填充.详细用法见oracle rpad函数
	 * 
	 * @param source
	 * @param padStr
	 * @param finalLength
	 * @return
	 */
	public static String rpad(String source, String padStr, int finalLength) {
		String ret = source;
		while (ret.length() < finalLength) {
			ret = ret + padStr;
		}
		return ret;
	}

	public static String join(int[] array, String separator) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = EMPTY;
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < array.length; i++) {
			sb.append(array[i] + separator);
		}
		if (sb.length() > 0) {
			sb.setLength(sb.length() - 1);
		}
		return sb.toString();
	}

	/**
	 * <p>
	 * Joins the elements of the provided array into a single String containing
	 * the provided list of elements.
	 * </p>
	 * 
	 * <p>
	 * No delimiter is added before or after the list. A <code>null</code>
	 * separator is the same as an empty String (""). Null objects or empty
	 * strings within the array are represented by empty strings.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.join(null, *)                = null
	 * StringUtils.join([], *)                  = &quot;&quot;
	 * StringUtils.join([null], *)              = &quot;&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], &quot;--&quot;)  = &quot;a--b--c&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], null)  = &quot;abc&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], &quot;&quot;)    = &quot;abc&quot;
	 * StringUtils.join([null, &quot;&quot;, &quot;a&quot;], ',')   = &quot;,,a&quot;
	 * </pre>
	 * 
	 * @param array
	 *            the array of values to join together, may be null
	 * @param separator
	 *            the separator character to use, null treated as ""
	 * @return the joined String, <code>null</code> if null array input
	 */
	public static String join(Object[] array, String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, 0, array.length);
	}

	/**
	 * <p>
	 * Joins the elements of the provided array into a single String containing
	 * the provided list of elements.
	 * </p>
	 * 
	 * <p>
	 * No delimiter is added before or after the list. A <code>null</code>
	 * separator is the same as an empty String (""). Null objects or empty
	 * strings within the array are represented by empty strings.
	 * </p>
	 * 
	 * <pre>
	 * StringUtils.join(null, *)                = null
	 * StringUtils.join([], *)                  = &quot;&quot;
	 * StringUtils.join([null], *)              = &quot;&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], &quot;--&quot;)  = &quot;a--b--c&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], null)  = &quot;abc&quot;
	 * StringUtils.join([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;], &quot;&quot;)    = &quot;abc&quot;
	 * StringUtils.join([null, &quot;&quot;, &quot;a&quot;], ',')   = &quot;,,a&quot;
	 * </pre>
	 * 
	 * @param array
	 *            the array of values to join together, may be null
	 * @param separator
	 *            the separator character to use, null treated as ""
	 * @param startIndex
	 *            the first index to start joining from. It is an error to pass
	 *            in an end index past the end of the array
	 * @param endIndex
	 *            the index to stop joining from (exclusive). It is an error to
	 *            pass in an end index past the end of the array
	 * @return the joined String, <code>null</code> if null array input
	 */
	public static String join(Object[] array, String separator, int startIndex,
			int endIndex) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = EMPTY;
		}

		// endIndex - startIndex > 0: Len = NofStrings *(len(firstString) +
		// len(separator))
		// (Assuming that all Strings are roughly equally long)
		int bufSize = (endIndex - startIndex);
		if (bufSize <= 0) {
			return EMPTY;
		}

		bufSize *= ((array[startIndex] == null ? 16 : array[startIndex]
				.toString().length()) + separator.length());

		StringBuffer buf = new StringBuffer(bufSize);

		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(array[i]);
			}
		}
		return buf.toString();
	}

	public static String subStringBetween(String msg, String beginChar,
			String endChar) {
		msg = nvl(msg);
		return msg.substring(msg.indexOf(beginChar) + 1, msg
				.lastIndexOf(endChar));
	}

	/**
	 * StringUtils.substringAfter(null, *) = null StringUtils.substringAfter("", *) = ""
	 * StringUtils.substringAfter(*, null) = ""
	 * StringUtils.substringAfter("abc", "a") = "bc"
	 * StringUtils.substringAfter("abcba", "b") = "cba"
	 * StringUtils.substringAfter("abc", "c") = ""
	 * StringUtils.substringAfter("abc", "d") = ""
	 * StringUtils.substringAfter("abc", "") = "abc"
	 */
	public static String substringAfter(String str, String separator) {
		if ((str == null) || (str.length() == 0)) {
			return str;
		}

		if (separator == null) {
			return EMPTY;
		}

		int pos = str.indexOf(separator);

		if (pos == -1) {
			return EMPTY;
		}

		return str.substring(pos + separator.length());
	}

	/**
	 * StringUtils.substringBefore(null, *) = null
	 * StringUtils.substringBefore("", *) = ""
	 * StringUtils.substringBefore("abc", "a") = ""
	 * StringUtils.substringBefore("abcba", "b") = "a"
	 * StringUtils.substringBefore("abc", "c") = "ab"
	 * StringUtils.substringBefore("abc", "d") = "abc"
	 * StringUtils.substringBefore("abc", "") = ""
	 * StringUtils.substringBefore("abc", null) = "abc"
	 */
	public static String substringBefore(String str, String separator) {
		if ((str == null) || (separator == null) || (str.length() == 0)) {
			return str;
		}

		if (separator.length() == 0) {
			return EMPTY;
		}

		int pos = str.indexOf(separator);

		if (pos == -1) {
			return str;
		}

		return str.substring(0, pos);
	}

	public static String chop(String orignalString, int length,
			String chopedString) {
		if (orignalString == null || orignalString.length() == 0) {
			return orignalString;
		}
		if (orignalString.length() < length) {
			return orignalString;
		}
		StringBuffer buffer = new StringBuffer(length);
		length = length * 2;
		int count = 0;
		int stringLength = orignalString.length();
		int i = 0;
		for (; count < length && i < stringLength; i++) {
			char c = orignalString.charAt(i);
			if (c < '\u00ff') {
				count++;
			} else {
				count += 2;
			}
			buffer.append(c);
		}
		if (i < stringLength) {
			buffer.append(chopedString);
		}
		return buffer.toString();
	}

	public static String getTabResult(String allFiles[],
			final String strIncomplete) {
		String result = null;
		String matchFiles[];
		int matchCount = 0;
		List<String> matchFileList = new ArrayList<String>();
		for (int i = 0; i < allFiles.length; i++) {
			if (allFiles[i].startsWith(strIncomplete)) {
				matchFileList.add(allFiles[i]);
				matchCount++;
			}
		}
		if (matchCount == 0) {
			return strIncomplete;
		}
		if (matchCount == 1) {
			return matchFileList.get(0);
		}

		// 有多个匹配的，取长度最短的那个返回(偷懒直接取第一个)
		if (matchCount > 1) {
			matchFiles = matchFileList.toArray(new String[] {});

			int minlen = matchFiles[0].length();
			int minindex = 0;
			for (int i = 0; i < matchFiles.length; i++) {
				String shortest = matchFiles[i];
				if (shortest.length() < minlen) {
					minlen = shortest.length();
					minindex = i;
				}
			}
			String shortest = matchFiles[minindex];
			// System.out.println("shortest="+shortest);
			String guess = shortest;
			int loopCount = 0;
			while (loopCount++ < 50) {
				boolean all_pass = true;
				for (int i = 0; i < matchFiles.length; i++) {
					if (!matchFiles[i].startsWith(guess)) {
						guess = guess.substring(0, guess.length() - 1);
						all_pass = false;
						break;
					}
				}
				if (all_pass) {
					break;
				} else {
					guess = guess.substring(0, guess.length());
					// System.out.println("next:"+guess);
				}
			}
			result = guess;

		}
		return result;
	}

	// GENERAL_PUNCTUATION 判断中文的“号 //
	// CJK_SYMBOLS_AND_PUNCTUATION 判断中文 的。号 /
	// HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号

	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	public static boolean isMessyCode(String strName) {
		if (strName.indexOf("?")!=-1) {
			return false;
		}
		
		Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
		Matcher m = p.matcher(strName);
		String after = m.replaceAll("");

		String temp = after.replaceAll("\\p{P}", "");

		char[] ch = temp.trim().toCharArray();
		float chLength = ch.length;
		float count = 0;
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (!Character.isLetterOrDigit(c)) { // 确定指定字符是否为字母或数字

				if (!isChinese(c)) {
					count = count + 1;
					return true;
				}
			}
		}
//		float result = count / chLength;
//		if (result > 0.4) {
//			return true;
//		} else {
			return false;
//		}
	}

	public static void main(String[] args) {
		String[] allFiles = new String[] { "afuck.txt", "abcdefg.txt",
				"abcdhij.txt", "ac.txt" };
		String strIncomplete = "abcd";
		System.out.println("result="
				+ StringUtil.getTabResult(allFiles, strIncomplete));
	}
}